//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;

namespace CommunityServer.Files.Controls
{

	public class EntryListing : FileGalleryTemplatedWebControl
	{
		private bool _isDataBound = false;
		CSContext csContext = CSContext.Current;

		#region Private Members

		protected int totalEntries;
		protected User user;

		#endregion

		#region Public Properties

		public int CurrentPage = 1;
		public int Count = 10;

		#endregion

		#region Child Controls

		private RepeaterPlusNone Entries;
		private PagingControl pagination, pagination2;
		private RssButton rssButton;
		private HyperLink uploadFile1, uploadFile2;
		private CommunityServer.Controls.FavoritePopupMenu FavoritePopupMenu;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Entries = (RepeaterPlusNone)FindControl( "Entries" );
			pagination = (PagingControl)FindControl( "Pagination" );
			pagination2 = (PagingControl) FindControl("Pagination2");
			rssButton = (RssButton)FindControl( "RssButton" );
			uploadFile1 = (HyperLink) FindControl("UploadFile1");
			uploadFile2 = (HyperLink) FindControl("UploadFile2");
			FavoritePopupMenu = (CommunityServer.Controls.FavoritePopupMenu) FindControl( "FavoritePopupMenu" );
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			Entries.ItemDataBound += new RepeaterItemEventHandler(Pictures_ItemDataBound);
			Entries.NoneItemsDataBound += new RepeaterItemEventHandler(Entries_NoneItemsDataBound);
		}

		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			// Grab the page number, if present
			if(this.Page.Request.QueryString["ppage"] != null)
				CurrentPage = int.Parse(this.Page.Request.QueryString["ppage"]);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			this.DataBind();
		}

		public override void DataBind()
		{
			if (_isDataBound)
				return;
			else
				_isDataBound = true;

			if (uploadFile1 != null)
				uploadFile1.NavigateUrl = FileGalleryUrls.Instance().EntryAdmin(csContext.ApplicationKey, -1);

			if (uploadFile2 != null)
				uploadFile2.NavigateUrl = FileGalleryUrls.Instance().EntryAdmin(csContext.ApplicationKey, -1);

			if (FavoritePopupMenu != null)
			{
				FavoritePopupMenu.SectionID = Folders.GetFolderID(csContext.ApplicationKey);
				FavoritePopupMenu.ApplicationType = ApplicationType.FileGallery;
			}

			base.DataBind ();
			BindEntries();
		}

		private void BindEntries()
		{
            CSContext context = csContext;
			user = context.User;

			// Setup the RSS button
			if (rssButton != null)
			{
				bool isAvailableToPublic = Permissions.ValidatePermissions(this.CurrentFolder, Permission.View, Users.GetAnonymousUser(true));
				if ((csContext.Tags == null || csContext.Tags.Length == 0) && CurrentFolder.EnableRssSyndication && (isAvailableToPublic || csContext.SiteSettings.EnableSecureSyndication))
				{
					if (isAvailableToPublic)
					{
						rssButton.NavigateUrl = FileGalleryUrls.Instance().Rss(context.ApplicationKey);
						rssButton.IsSecureFeed = false;
					}
					else
					{
						rssButton.NavigateUrl = SiteUrls.FormatUrlWithUserNameToken(FileGalleryUrls.Instance().Rss(context.ApplicationKey), csContext.User, false);
						rssButton.IsSecureFeed = true;
					}

					rssButton.IncludeAutodiscovery = true;
					rssButton.AutoDiscoveryTitle = this.CurrentFolder.Name;
				}
				else
					rssButton.Visible = false;
			}

			// Set the datasource and bind
			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			query.SectionID = CurrentFolder.SectionID;
			query.PageIndex = CurrentPage - 1;
			query.PageSize = Count;
			query.CategoryID = csContext.CategoryID;
			query.Tags = csContext.Tags;
			query.LogicallyOrTags = false;
			query.IncludeCategories = true;

			ThreadSet results = Components.Entries.GetEntries( query );

			// Setup the pagination
			pagination.CurrentPage = CurrentPage;
			pagination.TotalPages = (int)Math.Ceiling( (double) results.TotalRecords / (double)Count );
			pagination.PrefixText = "page";
			pagination.QueryName = "ppage";
			pagination.NavigateUrl = Page.Request.RawUrl;
			pagination.DataBind();

			if (pagination2 != null)
			{
				pagination2.CurrentPage = CurrentPage;
				pagination2.TotalPages = pagination.TotalPages;
				pagination2.PrefixText = "page";
				pagination2.QueryName = "ppage";
				pagination2.NavigateUrl = Page.Request.RawUrl;
				pagination2.DataBind();
			}

			Entries.DataSource = results.Threads;
			Entries.DataBind();
		}

		private void Pictures_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			Entry dataItem = e.Item.DataItem as Entry;

			switch( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					HyperLink name = (HyperLink)e.Item.FindControl( "Name" );
					IText description = TextControlHelper.Create(e.Item.FindControl( "Description" ));
					IText fileSize = TextControlHelper.Create(e.Item.FindControl( "FileSize"));
					HyperLink postedBy = (HyperLink)e.Item.FindControl( "PostedBy" );
					IText dateAdded = TextControlHelper.Create(e.Item.FindControl( "DateAdded" ));
					IText downloads = TextControlHelper.Create(e.Item.FindControl( "Downloads"));
					FileThumbnail thumbnail = (FileThumbnail) e.Item.FindControl("FileThumbnail");
					InlineTagEditorPanel InlineTagEditorPanel = (InlineTagEditorPanel) e.Item.FindControl("InlineTagEditorPanel");

					Control downloadLink = e.Item.FindControl("DownloadLink");
					Control editLink = e.Item.FindControl("EditLink");
					Control deleteLink = e.Item.FindControl("DeleteLink");

					if (name != null)
					{
						name.Text = dataItem.Subject;
						name.NavigateUrl = FileGalleryUrls.Instance().ViewEntry(csContext.ApplicationKey, dataItem.PostID);
					}
					
					if (description != null)
					{
						string desc = CommunityServer.Components.Formatter.RemoveHtml(dataItem.RenderedBody(PostTarget.Web));
						if(desc.Length > 50)
							description.Text = desc.Substring(0, 50) + "...";
						else
							description.Text = desc;
					}

					if (InlineTagEditorPanel != null)
					{
						InlineTagEditorPanel.PostID = dataItem.PostID;
						InlineTagEditorPanel.SelectedTags = dataItem.Categories;
					}

					if (downloads != null)
						downloads.Text = dataItem.Downloads.ToString();

					if (thumbnail != null)
						thumbnail.Post = dataItem;

					User user = csContext.User;
					if(!user.IsAnonymous)
						dateAdded.Text = user.GetTimezone(dataItem.PostDate).ToString(user.Profile.DateFormat);
					else
						dateAdded.Text = dataItem.PostDate.ToString(csContext.SiteSettings.DateFormat);

					if (fileSize != null)
					{
						if (dataItem.FileSize >= 0)
						{
							if(dataItem.FileSize < 1024)
								fileSize.Text = dataItem.FileSize.ToString() + " bytes";
							else if(dataItem.FileSize < 1024*1024)
								fileSize.Text = ((double)dataItem.FileSize / 1024).ToString("0.#") + "kB";
							else
								fileSize.Text = ((double)dataItem.FileSize / (1024*1024)).ToString("0.#") + "MB";
						}
						else
							fileSize.Text = "Unknown";
					}

					if (postedBy != null)
					{
						postedBy.Text = dataItem.DisplayName;
						postedBy.NavigateUrl = Globals.GetSiteUrls().UserProfile(dataItem.AuthorID);
					}

					RatingListing ratingListing = (RatingListing)e.Item.FindControl( "RatingListing" );
					if (ratingListing != null)
					{
						ratingListing.ApplicationKey = csContext.ApplicationKey;
						ratingListing.PictureID = dataItem.PostID;
						ratingListing.Entry = dataItem;
						ratingListing.DataBind();
					}

					if (downloadLink != null)
					{
						if (downloadLink is HyperLink)
						{
							((HyperLink) downloadLink).NavigateUrl = FileGalleryUrls.Instance().Download(dataItem);
							downloadLink.Visible = true;
						}
						else if (downloadLink is FileGalleryImageButton)
						{
							((FileGalleryImageButton) downloadLink).Post = dataItem;
							downloadLink.Visible = true;
						}
					}

					if (editLink != null)
					{
						if (Permissions.ValidatePermissions(Folders.GetFolder(csContext.ApplicationKey), Permission.Edit, user, dataItem))
						{
							if (editLink is HyperLink)
							{
								HyperLink editLinkHL = (HyperLink) editLink;
								editLinkHL.Visible = true;
								editLinkHL.NavigateUrl = FileGalleryUrls.Instance().EntryAdmin(csContext.ApplicationKey, dataItem.PostID);
							}
							else if (editLink is FileGalleryImageButton)
							{
								FileGalleryImageButton editLinkIB = (FileGalleryImageButton) editLink;
								editLinkIB.Post = dataItem;
								editLinkIB.Visible = true;
							}
						}
						else
						{
							editLink.Visible = false;
						}
					}

					if (deleteLink != null)
					{
						if (Permissions.ValidatePermissions(Folders.GetFolder(csContext.ApplicationKey), Permission.Delete, user, dataItem))
						{
							if (deleteLink is HyperLink)
							{
								HyperLink deleteLinkHL = (HyperLink) deleteLink;
								deleteLinkHL.Visible = true;
								deleteLinkHL.NavigateUrl = FileGalleryUrls.Instance().DeleteEntry(csContext.ApplicationKey, dataItem.PostID);
							}
							else if (deleteLink is FileGalleryImageButton)
							{
								FileGalleryImageButton deleteLinkIB = (FileGalleryImageButton) deleteLink;
								deleteLinkIB.Visible = true;
								deleteLinkIB.Post = dataItem;
							}
						}
						else
						{
							deleteLink.Visible = false;
						}
					}

					break;
			}
		}

		private void Entries_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{
			IText NoRecordsLabel = TextControlHelper.Create(e.Item.FindControl( "NoRecords" ));
			if (NoRecordsLabel != null)
				NoRecordsLabel.Text = FileGalleryResourceManager.GetString( "NoRecords" );
		}
	}
}
